package com.zzh.tools.utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;

import androidx.annotation.RequiresApi;


import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhangzhihao
 * @email zhangzhihao@gongjiangren.net
 * @date 2020-07-02
 * @desc
 */
public class ToolPhoneCheckUtils {


    /**
     * 判断字符串是否为数字
     *
     * @param str 传递的判断字符串
     * @return true为全部都是数字，false为不全部是数字
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 获取该应用的版本号：
     *
     * @return 返回版本名称
     */
    public static String getAppVersionName(Application application) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = application.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(application.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (versionName == null || versionName.length() <= 0) {
            versionName = "";
        }
        return versionName;
    }


    /**
     * 判断当前设备是手机还是平板，代码来自 Google I/O App for Android
     *
     * @return 平板返回 True，手机返回 False
     */
    public static boolean isPad(Application application) {
        return (application.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }


    /**
     * 获取手机屏幕宽度
     */
    public static int getScreamWidth(Application application) {

        Resources resources = application.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        int width3 = dm.widthPixels;
        return width3;
    }

    /**
     * @return 检查手机是否开启了更新下载可看的进度条
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static boolean isNotificationEnabled(Application application) {
        AppOpsManager appOps = (AppOpsManager) application.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = application.getApplicationInfo();
        String packageName = application.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        Class<?> appOpsClass = null;
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method method = appOpsClass.getMethod("checkOpNoThrow", Integer.TYPE, Integer.TYPE, String.class);
            Field notificationFieldValue = appOpsClass.getDeclaredField("OP_POST_NOTIFICATION");
            int value = (int) notificationFieldValue.get(Integer.class);
            return ((int) method.invoke(appOps, value, uid, packageName) == AppOpsManager.MODE_ALLOWED);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @param context 跳转到设置显示通知栏的
     */
    public static void gotoSetNotice(Context context) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            // android 8.0引导
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
        } else if (Build.VERSION.SDK_INT >= 21) {
            // android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", context.getPackageName());
            intent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else {
            // 其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static String md5Encode(String inStr) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        try {
            byte[] byteArray = inStr.getBytes("UTF-8");
            byte[] md5Bytes = md5.digest(byteArray);
            StringBuilder hexValue = new StringBuilder();
            for (byte md5Byte : md5Bytes) {
                int val = ((int) md5Byte) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return "";
    }


    /*****************************************  手机请求头的固定方法 ********************************/

    /**
     * 获取手机型号
     *
     * @return
     */
    public static String getPhoneModel() {
        String phoneModel = Build.MODEL;
        return phoneModel;
    }

    /**
     * 手机厂商
     *
     * @return
     */
    public static String getPhoneProducer() {
        String phoneProducer = Build.BRAND;
        return phoneProducer;
    }

    /**
     * 获取系统版本号
     *
     * @return
     */
    public static String getSystemVersion() {
        String systemVersion = Build.VERSION.RELEASE;
        return systemVersion;
    }

    /**
     * SDK 版本
     *
     * @return
     */
    public static String getSDKVersion() {
        String SDKVersion = Build.VERSION.SDK;
        return SDKVersion;
    }

    /**
     * 获取当前本地apk的版本
     *
     * @return
     */
    public static int getVersionCode(Application application) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = application.getPackageManager().
                    getPackageInfo(application.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取版本号名称
     *
     * @return
     */
    public static String getVersionName(Application application) {
        String verName = "";
        try {
            verName = application.getPackageManager().
                    getPackageInfo(application.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }


    /*
     * 手机品牌
     * */
    public static String getBrand() {
        String brand = Build.BRAND;
        return brand;
    }
    /*
     * 获取手机运行内存
     * */

    public static String getAvailMemory(Application application) {// 获取android当前可用内存大小  
        //获取运行内存的信息
        ActivityManager manager = (ActivityManager) application.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
        manager.getMemoryInfo(info);

        long totalMem = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            totalMem = info.totalMem;
        } else {
            totalMem = 10000L;
        }
        return totalMem + "";// 将获取的内存大小规格化  
    }

    /*
     * 获取手机总内存
     * */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public static String getTotalMemory() {
        final StatFs statFs = new StatFs(Environment.getDataDirectory().getPath());
        long size = statFs.getBlockSizeLong();
        long totalCounts = statFs.getBlockCountLong();
        long totalROMSize = totalCounts * size;
        return totalROMSize + "";
    }

    /*
     * 获取IMEI
     * */
    @SuppressLint("MissingPermission")
    public static String getIMEI(Application application) {
        StringBuilder deviceId = new StringBuilder();
        String imei = "";
        try {
            //实例化TelephonyManager对象
            TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(Context.TELEPHONY_SERVICE);
            //获取IMEI号
            imei = telephonyManager.getDeviceId();

        } catch (Exception e) {
//            e.printStackTrace();
//            LogUtils.e(e.getMessage());
        }
        return imei;
    }

    /*
     * 获取手机分辨率
     * */
    public static String getScs(Application application) {
        DisplayMetrics metrics  = application.getResources().getDisplayMetrics();
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        return width + "*" + height;
    }




    /**
     * 通过网络接口取
     *
     * @return
     */
    public static String getNewMac() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) {
                    continue;
                }

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return null;
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                String macAddress = res1.toString();
                String str2 = "";
                if (macAddress.contains(":")) {
                    String s[] = macAddress.split(":");
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < s.length; i++) {
                        sb.append(s[i]);
                    }
                    String str1 = sb.toString();//拆分后转换回字符串
                    str2 = str1.toUpperCase();
                    System.out.println(str2);
                } else {
                    str2 = macAddress.toUpperCase();
                }
                return str2;
//                return res1.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
